package com.example.tms.httpclient;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.IOException;

@Component
public class JiguangPush {

    @Value("${masterSecret}")
    private String masterSecret;

    @Value("${appKey}")
    private String appKey;

    /**
     * 添加访问授权
     */
    private String auth(){
        String str = appKey + ":" + masterSecret;
        byte[] key = str.getBytes();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return "Basic " + base64Encoder.encodeBuffer(key);
    }

    public JSONObject jiguangGet(String url){
        return JSONObject.parseObject(sendGetRequest(url, auth()));
    }

    public JSONObject jiguangPost(String url, String data){
        return JSONObject.parseObject(sendPostRequest(url, data, auth()));
    }

    /**
     * 发送GET请求
     */
    private static String sendGetRequest(String url, String authorization){
        //设置连接配置
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                .setSocketTimeout(5000).setConnectionRequestTimeout(5000).build();
        //创建HttpClient实例
        HttpClient httpClient = HttpClientBuilder.create().build();
        //创建GET的连接方式实例
        HttpGet httpGet = new HttpGet(url);
        //配置请求头
        httpGet.addHeader("content-type", "application/json");
        httpGet.addHeader("Accept", "application/json");
        httpGet.setHeader("Authorization",authorization.trim());
        System.out.println(authorization);
        httpGet.setConfig(requestConfig);
        try{
            //接收响应信息
            HttpResponse httpResponse = httpClient.execute(httpGet);
            return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        }catch (IOException e){
            return "{\"message\":\"IOException异常\"}";
        }finally {
            //释放连接
            httpGet.releaseConnection();
        }
    }

    /**
     * 发送Post请求（json格式）
     */
    private static String sendPostRequest(String url, String data, String authorization){
        //设置连接配置
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                .setSocketTimeout(5000).setConnectionRequestTimeout(5000).build();
        //创建HttpClient实例
        HttpClient httpClient = HttpClientBuilder.create().build();
        //创建Post的连接方式实例
        HttpPost httpPost = new HttpPost(url);
        //配置请求头
        httpPost.addHeader("content-type", "application/json");
        httpPost.addHeader("Accept", "application/json");
        httpPost.setHeader("Authorization",authorization.trim());
        httpPost.setConfig(requestConfig);
        try{
            //添加请求体信息
            StringEntity entity = new StringEntity(data, "UTF-8");
            httpPost.setEntity(entity);
            //接收响应信息
            HttpResponse httpResponse = httpClient.execute(httpPost);
            return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        }catch (IOException e){
            return "{\"message\":\"IOException异常\"}";
        }finally {
            //释放连接
            httpPost.releaseConnection();
        }
    }

}
